package com.kgis.fm.business.drawfeature {
	import com.kgis.fm.business.component.AttributeDialogTab;
	import com.kgis.fm.business.component.EntityDialog;
	import com.kgis.fm.business.event.RequestFormEvent;
	import com.kgis.fm.common.event.AddGeometryEvent;
	import com.kgis.fm.common.event.CommonEntityEvent;
	import com.kgis.fm.common.manager.MetaDataManager;
	import com.kgis.fm.flex.model.business.Entity;
	import com.kgis.fm.flex.model.business.ExtensionAttributes;
	import com.kgis.fm.flex.model.business.GeometryEntity;
	import com.kgis.fm.flex.model.metadata.Connectionship;
	import com.kgis.fm.flex.model.metadata.Ownership;
	import com.kgis.fm.flex.model.term.LegendEntry;
	import com.kgis.map.common.util.ResourceUtil;
	import com.kgis.map.constant.StringConstants;
	import com.kgis.map.events.DrawEvent;
	import com.kgis.map.feature.Feature;
	import com.kgis.map.geometry.AbstractGeometry;
	import com.kgis.map.geometry.PointGeometry;
	import com.kgis.map.geometry.basetype.Location;
	import com.kgis.mvc.CommandCompletionEvent;
	import com.kgis.mvc.ViewRegistry;
	import com.kgis.widgets.controls.Dialog;
	import com.kgis.widgets.managers.ConfirmHelper;
	import com.kgis.widgets.managers.ErrorManager;
	
	import fm.kgis.fm.service.FmEntityManagementService;
	import fm.kgis.fm.service.ServiceManager;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import spark.filters.DropShadowFilter;
	
	/**
	 * @author zhxiaomiao
	 * */
	[Event(name="{com.kgis.fm.business.event.RequestFormEvent.REQUEST_ID}", type="com.kgis.fm.business.event.RequestFormEvent")]
	[Event(name="{com.kgis.fm.common.event.CommonEntityEvent.REQUEST_ID}", type="com.kgis.fm.common.event.CommonEntityEvent")]
	public class DrawLineFeature extends AbstractDrawFeature {
		private var entityTypeId:Number;
		public var connEntities:ArrayCollection;
		public var ownerEntities:ArrayCollection;
		private var layerId:int = 0;
		private var drawFeature:Feature;
		private var dialog:EntityDialog;
		private var activeLE:LegendEntry;
		
		public function DrawLineFeature(entity:* = null) {
			super(entity);
			ViewRegistry.instance.eventBus.addParticipant(this);
		}
		
		override public function draw():void {
			snapFeatures = new ArrayCollection();
			connEntities = new ArrayCollection();
			ownerEntities=new ArrayCollection();
			drawHandler.snapClickCallback = snapClickCallback;
			drawHandler.active = true;
			//drawHandler.mouseDoubleClickEndEnabled=true;
			if (!map.hasEventListener(DrawEvent.DRAW_LINE_FEATURE_END)) {
				map.addEventListener(DrawEvent.DRAW_LINE_FEATURE_END, onDrawFeatureEnd);
			}
		}
		
		protected function snapClickCallback(features:ArrayCollection, snapPoint:PointGeometry):void {
			for each(var feature:Feature in features)
			{
				if (!snapFeatures.contains(feature)) {
					snapFeatures.addItem(feature);
				}
			}
			/*if (!snapFeatures.contains(feature)) {
				snapFeatures.addItem(feature);
				//默认捕捉两个点结束
				if (snapFeatures.length == 2) {
					if (feature && feature.geometry is PointGeometry) {
						var lastPoint:PointGeometry = feature.geometry as PointGeometry;
						map.dispatchEvent(new DrawEvent(DrawEvent.DRAW_END_POINT, null, new Location(lastPoint.x, lastPoint.y)));
					}
				}
			}*/
		}
		
		private function onDrawFeatureEnd(event:DrawEvent):void {
			//新增设施要保存的关系数据
			drawFeature = event.drawFeature;
			drawHandler.active = false;
			map.removeEventListener(DrawEvent.DRAW_LINE_FEATURE_END, onDrawFeatureEnd);
			//代表直接escape退出
			if (null == drawFeature) {
				return;
			}
			
			activeLE= MetaDataManager.getLegendEntryById( drawFeature.layer.id);
			//连接关系
			var connSnapFeatures:ArrayCollection=new ArrayCollection();
			var connections:ArrayCollection=MetaDataManager.getConnectionLayerByFnoCno(activeLE.fno,activeLE.cno);
			for each(var fea:Feature in snapFeatures)
			{
				for each(var conn:Connectionship in connections)
				{
					if(conn.clientFno==activeLE.fno&&conn.clientCno==activeLE.cno)
					{
						connSnapFeatures.addItem(fea);
					}
				}
			}

			
			
			//包含关系
			var ownerSnapFeatures:ArrayCollection=new ArrayCollection();
			var ownerships:ArrayCollection=MetaDataManager.getChildParentshipByFnoCno(activeLE.fno,activeLE.cno);
			for each(var fea:Feature in snapFeatures)
			{
				for each(var oship:Ownership in ownerships)
				{
					if(oship.ownerFno==activeLE.fno&&oship.ownerCno==activeLE.cno)
					{
						ownerSnapFeatures.addItem(fea);
					}
				}
			}
			
			for each(var fea:Feature in ownerSnapFeatures)
			{
				var ownerEntity:Entity=new Entity();
				ownerEntity.fno=activeLE.fno;
				ownerEntity.fid=11;
				ownerEntity.cno=31;
				
				
				var entityAttrs:ExtensionAttributes=new ExtensionAttributes();
				entityAttrs.put("KGM_CID",1);
			}
			
			layerId = drawFeature.layer.id;
			
			//属性为空
			if (null == entity) {
				
				//获得feature的layer id，然后找到eneitytypeid
				var legendEntry:LegendEntry = MetaDataManager.getLegendEntryById(drawFeature.layer.id);
				entityTypeId = legendEntry.leno;
				if (entityTypeId) {
					dispatchEvent(new RequestFormEvent([entityTypeId], RequestFormEvent.TYPE_NEW_ENTITY));
				}
			}
			else {
				//已经有entity，需要去数据库查询一遍是否有geometry，如果有提示已经有geometry，
				dispatchEvent(new CommonEntityEvent([entity.entityTypeId, entity.id, map.logicalMapId], CommonEntityEvent.TYPE_FIND_GEOMETRYENTITY_BYID));
			}
		}
		
		
		
		override public function drawEnd():void {
			drawHandler.active = false;
			map.removeEventListener(DrawEvent.DRAW_LINE_FEATURE_END, onDrawFeatureEnd);
		}
		
		private function saveEntity():void {
			entity.geometry = drawFeature.geometry;
			/**
			 * logicMapId
			 * */
			entity.detailId = map.logicalMapId;
			dispatchEvent(new CommonEntityEvent([entity,connEntities,ownerEntities], CommonEntityEvent.TYPE_SAVE_GEOMETRYENTITY));
		}
		
		[ResponseHandler("{com.kgis.fm.business.event.RequestFormEvent.RETURN_ID}")]
		public function onRequestFormEvent(event:CommandCompletionEvent):void {
			entity = event.result;
			
			var relations:ArrayCollection = MetaDataManager.getRelationshipLayerIds(entityTypeId);
			dialog = new EntityDialog();
			dialog.formType = AttributeDialogTab.FORM_TYPE_EDIT;
			dialog.entityTypeId = entityTypeId;
			if(!entity)
			{
				entity=new GeometryEntity();
			}
			var sridtype:String=MetaDataManager.getGeneralParameterByName("MAINCOORDINATESSYSTEM");
			if(sridtype=="1")
			{
				AbstractGeometry(drawFeature.geometry).srid=4326;
			}
			entity.geometry = drawFeature.geometry;
			
			entity.detailId = map.logicalMapId;
			entity.fno=activeLE.fno;
			entity.cno=activeLE.cno;
			
			//弹出属性框
			dialog.entity = entity;
			dialog.submitFun = submitFunCallBack;
			dialog.cancelBack = onCancelBtn;
			PopUpManager.addPopUp(dialog, this.map.root, true);
			PopUpManager.centerPopUp(dialog);
	
			
		
		}
		
		protected function onCancelBtn():void {
			map.getLayerById(layerId).redraw();
		}
		
		protected function submitFunCallBack():void {
			dispatchEvent(new CommonEntityEvent([entity, connEntities,ownerEntities], CommonEntityEvent.TYPE_SAVE_GEOMETRYENTITY));
		}
		
		[ResponseHandler("{com.kgis.fm.common.event.CommonEntityEvent.RETURN_ID}")]
		public function onCommandEvent(event:CommandCompletionEvent):void {
			
			var request:CommonEntityEvent = event.request as CommonEntityEvent;
			switch (request.actionType) {
				case CommonEntityEvent.TYPE_SAVE_GEOMETRYENTITY:
					//entity = event.result;
					//map.getLayerById(layerId).redraw();
					if (dialog) {
						dialog.loadingState = Dialog.LOADED;
						PopUpManager.removePopUp(dialog);
					}
					
					//得到编辑的属性
					var extAttr:ExtensionAttributes=new ExtensionAttributes();
					extAttr["KGM_CID"]=1;
					extAttr["KGM_ID"]=1;
					extAttr["KGM_SNO"]=200;
					for each(var attr:Object in dialog.propertyValueList)
					{
						extAttr[attr.field]=attr.value;
					}		
					entity.attributes=extAttr;
					//保存到数据库
					ServiceManager.getFmEntityManagementService().createGeometryEntity(entity as Entity,null,null);
					
					
					//dispatchEvent(new AddGeometryEvent(entity, AddGeometryEvent.TYPE_ADD_GEOMETRY_END));
					drawEnd();
					
					
					break;
				case CommonEntityEvent.TYPE_FIND_GEOMETRYENTITY_BYID:
					entity = event.result;
					if (null != entity.geometry) {
						ConfirmHelper.showConfirmDialog("", ResourceUtil.getString(StringConstants.FEATURE_HAS_GEOMETRY), function(evt:CloseEvent):void {
							if (evt.detail == Alert.YES) {
								saveEntity();
							}
							else {
								//刷新图层
								map.refreshAllFeatureLayer();
								return;
							}
						});
					}
					else {
						saveEntity();
					}
					break;
			}
			
		}
	}
}